﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Needle.DevToolkit.Traits;
using Needle.Utils.Collections;

namespace Needle.DevToolkit.UI.Controls
{
    public class ItemTreeNode : TreeNode
    {
        public ItemTreeNode(IItem item)
        {
            IName name = null;
            if (item.TryGetTrait<IName>(out name))
            {
                Text = name.Name;
            }
            else
            {
                Text = item.ToString();
            }
            Tag = item;

            var parent = item.GetTrait<IParent>();
            if (parent != null)
            {
                parent.Items.CollectionChanged +=  OnItemsCollectionChanged ;
                foreach (var child in parent.Items)
                    Nodes.Add(new ItemTreeNode(child));
            }
           
        }

        void OnItemsCollectionChanged(object sender, CollectionChangeEventArgs<IItem> e)
        {
            switch (e.Change)
            {
                case CollectionChange.Cleared:
                    Nodes.Clear();
                    break;
                case CollectionChange.Removed:
                    foreach (TreeNode node in Nodes)
                    {
                        if (node.Tag == e.Item)
                        {
                            Nodes.Remove(node);
                            break;
                        }
                    }
                    break;
                case CollectionChange.Inserted:
                    if (Nodes.Count > e.Index)
                        Nodes.Insert(e.Index, new ItemTreeNode(e.Item));
                    else
                        Nodes.Add(new ItemTreeNode(e.Item));
                    break;
            }
        }
    }
}
